﻿Imports TNCDAL
Imports TNCBAL
Imports HTLibrary

Public Class ucPort
    Private ctlPort As New CPortController
    Private currPort As tblPort

    Private Sub ucPort_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        InitGridView()
        CViewer.BindCountriesToComboBox(cboCountry)
        CViewer.BindCountriesToCombobox_2(cboSearchCountries)
        BindGridView("", -1)
    End Sub
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(dgPorts)
        ' Add any initialization after the InitializeComponent() call.

    End Sub

#Region "Utilities"
    Public Sub InitGridView()
        dgPorts.AllowUserToAddRows = False
        dgPorts.AllowUserToDeleteRows = False
        dgPorts.ReadOnly = True
    End Sub

    Public Sub BindComboCountries(ByVal cbo As DevComponents.DotNetBar.Controls.ComboBoxEx)
        Dim ctrlCountries As New CCountryController
        Dim countries = ctrlCountries.SelectAllRecord
        Dim emptyTable As tblCountry() = {New tblCountry With {.ID_Country = 0, .CountryName = "-------"}}
        Dim countries2 = (From e In emptyTable Select e).Union(countries).ToList
        With cbo
            .DataSource = countries2
            .DisplayMember = "CountryName"
            .ValueMember = "ID_Country"
        End With
    End Sub

    Public Sub BindGridView(ByVal sPort As String, ByVal idCountry As Integer)
        EnableButtons(False)
        Dim query As IQueryable = ctlPort.SelectAllRecord3(sPort, idCountry)
        Dim source As New BindingSource
        source.DataSource = query
        dgPorts.DataSource = source
        BindingNavigator1.BindingSource = source
        dgPorts.Columns("Id_Port").Visible = False
        dgPorts.Columns("ID_Country").Visible = False
        dgPorts.Columns("CountryName").HeaderText = "Country"
        dgPorts.Columns("Port").Width = 250
        If (dgPorts.Rows.Count = 0) Then
            btnEdit.Enabled = False
            btnDel.Enabled = False
            txtPortName.Text = ""
        Else
            btnEdit.Enabled = True
            btnDel.Enabled = True
        End If
    End Sub
    ''' <summary>
    ''' Show/hide command buttons
    ''' </summary>
    ''' <param name="val"></param>
    ''' <remarks></remarks>
    Private Sub EnableButtons(ByVal val As Boolean)
        btnUpdate.Enabled = val
        btnCancel.Enabled = val

        btnAdd.Enabled = Not val
        btnEdit.Enabled = Not val
        btnDel.Enabled = Not val

        dgPorts.Enabled = Not val

        txtPortName.ReadOnly = Not val
        cboCountry.Enabled = val

        If (dgPorts.Rows.Count < 1) Then
            btnEdit.Enabled = False
            btnDel.Enabled = False
        End If
    End Sub

    Public Sub FillCustomerForm()
        If (currPort IsNot Nothing) Then
            'show result
            txtPortName.Text = currPort.Port
            If (currPort.ID_Country Is Nothing) Then
                cboCountry.SelectedIndex = -1
            Else
                cboCountry.SelectedValue = currPort.ID_Country
            End If
        Else
            txtPortName.Text = ""
            cboCountry.SelectedIndex = -1
        End If
        
    End Sub

    Public Sub RefreshForm()
        txtPortName.Text = ""
        cboCountry.SelectedIndex = -1
    End Sub
    Private Function FindIndexOfPortInGrid(ByVal id As Integer) As Integer
        Dim index As Integer = -1
        For Each row As DataGridViewRow In dgPorts.Rows
            If (row.Cells("ID_Port").Value = id) Then
                index = row.Index
                Exit For
            End If
        Next
        Return index
    End Function
#End Region

#Region "Buttons' Events"
    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        EnableButtons(True)
        RefreshForm()
        'Init obj
        currPort = New tblPort
        txtPortName.Focus()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        EnableButtons(True)
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        ''kiểm tra xem người sử dụng đã chọn country hay chưa?
        If (cboCountry.SelectedIndex = 0 Or cboCountry.Text = "") Then
            MessageBox.Show("You should select country of this port!")
            Return
        End If

        'kiểm tra xem tên có bị trùng hay không
        If (ctlPort.CheckExists(txtPortName.Text, currPort.ID_Port)) Then
            MessageBox.Show("This port exists. Please choose another port name.")
            Return
        End If
        Dim idCountry As Integer = -1
        With currPort
            .Port = txtPortName.Text
            .ID_Country = cboCountry.SelectedValue
            .IsActive = True
            idCountry = cboCountry.SelectedValue
        End With
        Dim idCurr As Integer = currPort.ID_Port
        If currPort.ID_Port > 0 Then
            ctlPort.UpdateRecordWithoutAttach(currPort)
            'ghi log
            Dim objLogController As New LogController
            objLogController.Insert(enumAction.Edit, "Port: " & currPort.Port)
        Else
            ctlPort.InsertRecord(currPort)
            idCurr = currPort.ID_Port
            'ghi log
            Dim objLogController As New LogController
            objLogController.Insert(enumAction.Add, "Port: " & currPort.Port)
            'Refresh gridview
            txtSearchPortName.Text = ""
        End If
        'Refresh gridview
        If (idCountry <> cboSearchCountries.SelectedValue) Then
            cboSearchCountries.SelectedValue = idCountry
        End If
        BindGridView("", cboSearchCountries.SelectedValue)
        Dim indexRow As Integer = -1
        'lấy ra vị trí của port vừa thêm hoặc chỉnh sửa vào
        indexRow = FindIndexOfPortInGrid(idCurr)
        If (indexRow > -1) Then
            'Set current row
            dgPorts.CurrentCell = dgPorts.Rows(indexRow).Cells(1)
            dgPorts.Rows(indexRow).Selected = True
        End If
        'Refresh buttons
        EnableButtons(False)
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Try
            Dim _id As Integer = dgPorts.CurrentRow.Cells("ID_Port").Value
            currPort = ctlPort.SelectRecordByID(_id)
        Catch ex As Exception
        End Try
        FillCustomerForm()
        EnableButtons(False)
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        If (MessageBox.Show("Bạn có chắc muốn xoá " + currPort.Port + " ?", "Xác nhận", MessageBoxButtons.YesNo) = vbYes) Then
            'xoa khoi du lieu bằng cách set IsActive = false
            currPort.IsActive = False
            ctlPort.UpdateRecordWithoutAttach(currPort)
            'ghi log
            Dim objLogController As New LogController
            objLogController.Insert(enumAction.Delete, "Port: " & currPort.Port)
            'load lại grid
            BindGridView(txtSearchPortName.Text, cboSearchCountries.SelectedValue)
        End If
    End Sub
    Private Sub ButtonX1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btGetAll.Click
        'bỏ lọc đi
        txtSearchPortName.Text = ""
        cboSearchCountries.SelectedIndex = 0
        BindGridView("", -1)
    End Sub
#End Region

#Region "dgCountries's Events"
    Private Sub dgPorts_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgPorts.SelectionChanged
        'Load info
        Try
            Dim id As Integer = dgPorts.CurrentRow.Cells("ID_Port").Value
            currPort = ctlPort.SelectRecordByID(id)

            'Kiểm tra nếu đang cập nhật/thêm mới thì không hiển thị dữ liệu
            If btnUpdate.Enabled Then
                Return
            End If

            'Fill company's fields
            FillCustomerForm()

        Catch ex As Exception

        End Try
    End Sub
#End Region

#Region "Other controls' Events"
    Private Sub txtSearchPortName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearchPortName.TextChanged
        Dim id As Integer = -1
        Try
            id = CType(cboSearchCountries.SelectedItem, tblCountry).ID_Country
        Catch ex As Exception
        End Try
        BindGridView(txtSearchPortName.Text, id)
    End Sub

    Private Sub cboSearchCountries_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboSearchCountries.SelectedIndexChanged
        Dim id As Integer = -1
        Try
            id = CType(cboSearchCountries.SelectedItem, tblCountry).ID_Country
        Catch ex As Exception
        End Try
        BindGridView(txtSearchPortName.Text, id)
    End Sub
#End Region

    
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        CViewer.BindCountriesToComboBox(cboCountry)
        CViewer.BindCountriesToCombobox_2(cboSearchCountries)
    End Sub
End Class
